/*******************************************************************************
Copyright (C), 200{x}, Borqs Tech. Co., Ltd.
File Name: 
    client/lapi_ipc.c
Description: 
    
History:  
    Date          Author                         Comments
    -----------   ---------------------------    --------------------
    Mar-24-2008   anle.zhou@borqs.com            Created
*******************************************************************************/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include "lapi_comm.h"
#include "lapi_ipc.h"

LAPI_INT32 LAPI_SendMsg(const LAPI_INT32 fd, const LAPI_UINT8* buff, const LAPI_UINT32 len)
{
    LAPI_INT32 ret;

    if (len > LAPI_MSG_MAX) {
        LAPI_ERR("Message too long");
        return -1;
    }

    ret = write(fd, buff, len);
    if (ret < 0) {
        LAPI_ERR("Failed to send message to %d (%d-%s)", fd, errno, strerror(errno));
        return -1;
    }
    LAPI_DBG("Send message to %d", fd);

    /*int i;
    for (i=0; i<ret; i++)
        LAPI_DBG("send %d = %d, 0x%x", i, buff[i], buff[i]);*/

    return ret;
}

LAPI_INT32 LAPI_RecvMsg(const LAPI_INT32 fd, LAPI_UINT8* buff)
{
    LAPI_INT32 ret;

    ret = read(fd, buff, LAPI_MSG_MAX);
    if (ret < 0) {
        LAPI_ERR("Failed to recv message from %d (%d-%s)", fd, errno, strerror(errno));
        return -1;
    }
    LAPI_DBG("Recv message from %d", fd);

    /*int i;
    for (i=0; i<ret; i++)
        LAPI_DBG("recv %d = %d, 0x%x", i, buff[i], buff[i]);*/
    return ret;
}

void LAPI_MSG_Handler(LAPI_MSG_TYPE_E type, LAPI_INT8 *S)
{
    LAPI_UINT32 i;
    for(i = 0; i < sizeof(LAPI_MSG_ARRAY)/sizeof(LAPI_MSG_H); i++)
    {
        if(LAPI_MSG_ARRAY[i].id == type)
        {
            strcpy(S, LAPI_MSG_ARRAY[i].string);
            break;
        }
    }
}

void LAPI_PrintReq(const LAPI_MSG_REQ_S* msg)
{
#ifdef LAPI_DEBUG
    if (msg == NULL)
        return;

    LAPI_INT8 *reqstr;
    reqstr = malloc(LAPI_MSGSTRING_LONG);
    memset(reqstr, 0, LAPI_MSGSTRING_LONG);
    LAPI_DBG("Session ID: %d", msg->sessionID);
    LAPI_DBG("Message Type: %d", msg->msgType);
    LAPI_MSG_Handler(msg->msgType, reqstr);
    LAPI_DBG("Get request %s", reqstr);
    free(reqstr);
#endif
}

void LAPI_PrintRsp(const LAPI_MSG_RSP_S* msg)
{
#ifdef LAPI_DEBUG
    if (msg == NULL)
        return;

    LAPI_INT8 *rspstr;
    rspstr = malloc(LAPI_MSGSTRING_LONG);
    memset(rspstr, 0, LAPI_MSGSTRING_LONG);
    LAPI_DBG("Session ID: %d", msg->sessionID);
    LAPI_DBG("Message Type: %d", msg->msgType);
    LAPI_DBG("Result: %d", msg->result);
    LAPI_MSG_Handler(msg->msgType, rspstr);
    LAPI_DBG("Sent response %s", rspstr);
    free(rspstr);
    //LAPI_DBG("Data: %p", msg->data);
    /*if (msg->msgType == LAPI_RSP_GETLOCATION) {
        int i;
        for (i=0; i<LAPI_RSP_DATA_MAX; i++)
            LAPI_DBG("0x%02x", msg->data[i]);
    }*/
#endif
}
